<?php


namespace app\community\controller;


use app\common\controller\Common;
use app\common\controller\Together;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;
use think\Url;
use think\Validate;

class Exchange extends Controller
{

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        //直接实例化request类方便后期调用
        $this->request = $request;
        if(!Session::get("id")){
            $this->error('请先登录',Url::build("login/login/login"));
        }
    }

    public function _initialize()
    {
        //获取平台标题
        $platform = Db::name("config_platform")->find();
        $this->assign("platform", $platform);
    }

    //兑换产品列表
    public function index(){
        $keyword = '';
        $classify_id = '';
        $where = [];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where['a.title'] = ['like', "%{$keyword}%"];
        }
        if(!empty($_GET['classify_id'])){
            $classify_id = $_GET['classify_id'];
            $where['a.classify_id'] = $classify_id;
        }
        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("system_exchange")->alias("a")
                    ->join("system_article_classify b","a.classify_id = b.id")
                    ->join("community_colony c","b.colony_id = c.id")
                    ->field("a.*,c.name as colony_name")
                    ->where($where)->limit($start,$limit)->order("id desc")->select();
                $count = Db::name("system_exchange")->alias("a")
                    ->join("system_article_classify b","a.classify_id = b.id")
                    ->join("community_colony c","b.colony_id = c.id")->where($where)->count("*");

                //审核状态
                $audit = Db::name("config_attribute")->where(['key' => "audit"])->value("value");
                $audit = explode("|", $audit);
                foreach ($audit as $k => $v) {
                    $audit[$k + 1] = $v;
                }
                unset($audit[0]);

                foreach ($list as $k => $v) {
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                    $v['thumb'] = empty($v['thumb']) ? "/static/images/nopic-107.png" : $v['thumb'];
                    $list[$k]['thumb'] = "<img src='".$v['thumb']."' style='max-height:50px;max-width:50px;'>";
                }
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }
        $assign = [
            'keyword' => $keyword,
            'classify_id'=>$classify_id
        ];
        $this->assign($assign);
        return $this->fetch('index');

    }

    //档案模型字段
    public function record(){
        //审核状态
        $audit = Db::name("config_attribute")->where(['key' => "enable_status"])->value("value");
        $audit = explode("|", $audit);
        foreach ($audit as $k => $v) {
            $audit[$k + 1] = $v;
        }
        unset($audit[0]);

        //获取管理的景区
        $Together = new Together();
        $colony = $Together->findColony();

        //查询档案模型栏目 $colony[0]['id']
        $classify = Db::name("system_article_classify")->where(['colony_id'=>$colony[0]['id'],'type'=>10])->select();

        //兑换角色
        $type = [1=>"志愿者",2=>"党员"];

        $assign = [
            "colony"=>$colony,
            "audit" => $audit,
            "classify"=>$classify,
            "type"=>$type
        ];
        return $assign;
    }


    //产品详细信息
    public function detail(){
        $record = $this->record();
        $this->assign($record);
        $classify_id = $_GET['classify_id'];
        $this->assign("classify_id",$classify_id);
        if(empty($_GET['id'])){
            return $this->fetch('addData');
        }else {
            $id = $_GET['id'];
            $where['id'] = $id;
            $detail = Db::name("system_exchange")->where($where)->find();

            //所属景区
            $detail['colony_id'] = Db::name("system_article_classify")->where(['id'=>$detail['classify_id']])->value("colony_id");

            //查询档案模型栏目 $colony[0]['id']
            $classify = Db::name("system_article_classify")->where(['colony_id'=>$detail['colony_id'],'type'=>10])->select();
            $this->assign("classify",$classify);

            //商品图组
            if(!empty($detail['images'])){
                $detail['images'] = explode(";", $detail['images']);
            }

            $this->assign("detail",$detail);
            return $this->fetch('editData');
        }
    }

    //添加兑换产品
    public function doExchange(){

        $common = new Common();
        try {
            $rule = [
                ["classify_id", "require", "请关联栏目"],
                ["title", "require", "请输入商品名称"],
                ["thumb", "require", "请选择缩略图"],
                ["integral", "require", "请填写积分"],
                ["content", "require", "请输入权益介绍"],
                ["inventory", "require", "请输入库存"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();
            $thisWechat = Session::get("thisWechat");
            $value['uniacid'] = $thisWechat['id'];
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }

            if (!empty($value['images'])) {
                $value['images'] = implode(";", $value['images']);
            } else {
                unset($value['images']);
                $value['images'] = '';
            }


            if (empty($value['id'])) {
                $value['addtime'] = time();
                $value['add_id'] = Session::get("id");
                $value['table'] =  Session::get("table");
                $id = Db::name("system_exchange")->insertGetId($value);
                $log['remark'] = "用户【" . Session::get("user_name") . "】添加积分商品【".$value['title']."】,商品id【" . $id . "】";
            } else {
                $id = $value['id'];
                $value['updatetime'] = time();
                $value['update_id'] = Session::get("id");
                $value['update_table'] =  Session::get("table");
                Db::name("system_exchange")->update($value);
                $log['remark'] = "用户【" . Session::get("user_name") . "】更新积分商品【".$value['title']."】的信息,商品id【" . $id . "】";
            }
            $log['controller'] = "Exchange";
            $log['methods'] = "doExchange";
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "添加成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //删除兑换产品
    public function delExchange(){
        $common = new Common();
        try {
            $id = $_POST['id'];
            $navList = Db::name("system_exchange")->where(['id' => ['in', $id]])->field("id,title")->select();
            foreach ($navList as $k=>$v){
                $log['remark'] = "账号【" . Session::get("user_name") . "】删除积分商品信息,商品名称【".$v['title']."】删除id【" . $v['id'] . "】";
                $log['controller'] = "Exchange";
                $log['methods'] = "delExchange";
                $common->addLog($log);
            }
            Db::name("system_exchange")->where(['id' => ['in', $id]])->delete();
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //兑换列表
    public function order(){
        $keyword = '';
        $where = [];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where['a.title'] = ['like', "%{$keyword}%"];
        }

        if (!empty($_GET['order_sn'])) {
            $order_sn = $_GET['order_sn'];
            $where['a.order_sn'] = ['like', "%{$order_sn}%"];
        }

        if (!empty($_GET['nickname'])) {
            $nickname = $_GET['nickname'];
            $where['b.nickname'] = ['like', "%{$nickname}%"];
        }


        $status = [1=>"待核销",2=>"已核销",3=>"已驳回"];
        $type = [1=>'志愿者',2=>"党员"];

        //获取管理的景区
        $Together = new Together();
        $colony = $Together->findColony();


        $colony = array_column($colony,"id");
        $where['a.colony_id'] = ['in',$colony];

        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("community_exchange_order")->alias("a")
                    ->join("admin_fans b","a.fans_id = b.id")
                    ->join("community_colony c","a.colony_id = c.id")
                    ->field("a.*,b.nickname,c.name c_name")
                    ->where($where)->limit($start,$limit)->order("id desc")->select();
                $count = Db::name("community_exchange_order")->alias("a")
                    ->join("admin_fans b","a.fans_id = b.id")
                    ->join("community_colony c","a.colony_id = c.id")
                    ->field("a.*,b.nickname")
                    ->where($where)->count("*");
                foreach ($list as $k => $v) {
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                    $v['thumb'] = empty($v['thumb']) ? "/static/images/nopic-107.png" : $v['thumb'];
                    $list[$k]['thumb'] = "<img src='".$v['thumb']."' style='height:50px'>";
                    $list[$k]['status'] = $status[$v['status']];
                    if($v['type']==1){
                        $name = Db::name("system_registration")->where(['id'=>$v['role_id']])->value("name");
                    }else{
                        $name = Db::name("system_record")->where(['id'=>$v['role_id']])->value("name");
                    }
                    $list[$k]['name'] = "【".$type[$v['type']]."】".(empty($name)?"":$name);
                }
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }
        $assign = [
            'keyword' => $keyword,
        ];
        $this->assign($assign);
        return $this->fetch('order');
    }

    //查询兑换详细信息
    public function orderDetail(){
        $id = $_POST['id'];
        $status = [1=>"待核销",2=>"已核销",3=>"已驳回"];
        $type = [1=>'志愿者',2=>"党员"];
        $where['id'] = $id;
        $detail = Db::name("community_exchange_order")->where($where)->find();
        //所属小区
        $detail['colony_name'] = Db::name("community_colony")->where(['id'=>$detail['colony_id']])->value('name');
        //获取粉丝信息
        $fans = Db::name("admin_fans")->where(['id'=>$detail['fans_id']])->field("avatar,nickname,openid,xcx_openid,realName,mobile")->find();
        $detail = array_merge($detail,$fans);
        //查询身份信息
        if($detail['type']==1){
            $name = Db::name("system_registration")->where(['id'=>$detail['role_id']])->value("name");
        }else{
            $name = Db::name("system_record")->where(['id'=>$detail['role_id']])->value("name");
        }
        $detail['name'] = empty($name)?"":$name;
        $detail['type'] = $type[$detail['type']];
        $detail['status'] = $status[$detail['status']];
        $this->assign('detail',$detail);
        return view('orderDetail');
    }

    //更改兑换状态
    public function updateStatus(){
        $status_val = [1=>"待核销",2=>"已核销",3=>"已驳回"];
        try {
            $id = $_POST["id"];
            if (empty($_POST['status'])) {
                throw new Exception("请选择操作类型");
            }
            $detail = Db::name("community_exchange_order")->where(['id' => $id])->find();
            $status = $_POST['status'];
            if($detail['status']!=1){
                throw new Exception("非法操作");
            }
            $data['status'] = $status;
            $data['updatetime'] = time();
            $data['update_id'] = Session::get("id");
            Db::name("community_exchange_order")->where(['id' => $id])->update(['status' => $status]);
            //驳回操作
            if($status == 3){
                if($detail['type']==1){
                    $before_number = Db::name("system_registration")->where(['id'=>$detail['role_id']])->value("integral");
                    Db::name("system_registration")->where(['id'=>$detail['role_id']])->setInc("integral",$detail['integral']);
                    //记录积分明细
                    $log['reg_id'] = $detail['role_id'];
                    $log['remark'] = "账户【" . Session::get("user_name") . "】驳回兑换信息，驳回兑换产品【".$detail['title']."】关联id【".$id."】";
                    $log['type'] = "integral";
                    $log['type_status'] = 1;
                    $log['number'] = $detail['integral'];
                    $log['before_number'] = $before_number;
                    $log['after_number'] = $before_number+$detail['integral'];
                    $log['addtime'] = time();
                    $log['operator_id'] = Session::get("id");
                    $log['auto'] = Session::get("auto");
                    Db::name("system_registration_log")->insert($log);

                }else{
                    $before_number = Db::name("system_record")->where(['id'=>$detail['role_id']])->value("integral");
                    Db::name("system_record")->where(['id'=>$detail['role_id']])->setInc("integral",$detail['integral']);
                    //记录积分明细
                    $log['reg_id'] = $detail['role_id'];
                    $log['remark'] = "账户【" . Session::get("user_name") . "】驳回兑换信息，驳回兑换产品【".$detail['title']."】关联id【".$id."】";
                    $log['type'] = "integral";
                    $log['type_status'] = 1;
                    $log['number'] = $detail['integral'];
                    $log['before_number'] = $before_number;
                    $log['after_number'] = $before_number+$detail['integral'];
                    $log['addtime'] = time();
                    $log['operator_id'] = Session::get("id");
                    $log['auto'] = Session::get("auto");
                    Db::name("system_record_log")->insert($log);
                }
                Db::name("system_exchange")->where(['id'=>$detail['exchange_id']])->setInc("inventory");
            }
            $common = new Common();
            $log['remark'] = "账户【" . Session::get("user_name") . "】将兑换产品【".$detail['title']."】的状态更新为【".$status_val[$status]."】,关联ID【" . $id . "】";
            $log['controller'] = "Exchange";
            $log['methods'] = "updateStatus";
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    public function delOrder(){
        $common = new Common();
        try {
            $id = $_POST['id'];
            Db::name("community_exchange_order")->where(['id' => ['in', $id]])->delete();
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


}